﻿using DevExpress.Charts.Model;
using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using DevExpress.Utils.About;
using DevExpress.Utils.Svg;
using HandyControl.Controls;
using HandyControl.Data;
using HandyControl.Properties.Langs;
using PlaceOrder_Client.Events;
using PlaceOrder_Client.Models.Common;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Chat;
using Prism.DryIoc;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Threading;

namespace PlaceOrder_Client.ViewModels
{
    /// <summary>
    /// 聊天窗口的ViewModel
    /// </summary>
    /// 
    public class ChatMessageViewModel : BindableBase
    {
        #region 依赖属性
        private ObservableCollection<ChatWindowViewModel> chatWindows;

        public ObservableCollection<ChatWindowViewModel> ChatWindows
        {
            get { return chatWindows; }
            set { chatWindows = value; RaisePropertiesChanged(); }
        }

        //public ObservableCollection<ChatWindowViewModel> ChatWindows { get; set; }
        private ObservableCollection<ChatBroker> brokerChatList;

        /// <summary>
        /// List绑定对象
        /// </summary>
        public ObservableCollection<ChatBroker> BrokerChatList
        {
            get { return brokerChatList; }
            set { brokerChatList = value;RaisePropertiesChanged(); }
        }

        private ObservableCollection<string> brokerList;

        /// <summary>
        /// 多选绑定对象
        /// </summary>
        public ObservableCollection<string> BrokerList
        {
            get { return brokerList; }
            set { brokerList = value;RaisePropertiesChanged(); }
        }

      


        private ObservableCollection<ChatMessage> messageDataList;

        public ObservableCollection<ChatMessage> MessageDataList
        {
            get { return messageDataList; }
            set { messageDataList = value; }
        }


        private object subContent;

        public object SubContent
        {
            get { return subContent; }
            set { subContent = value; RaisePropertiesChanged(); }
        }


        private int uniformNumber;

        public int UniformNumber
        {
            get { return uniformNumber; }
            set { uniformNumber = value; RaisePropertiesChanged(); }
        }

        #endregion


        #region 命令
        public DelegateCommand<ChatBroker> NavigateChatWindowCmd => new(RefreshChatBox);


        #endregion
        private readonly ChatWindowViewModel _chatWindowViewModel;

        public ChatMessageViewModel()
        {

        }
        private readonly IDailyData _dailyData;
        public ChatMessageViewModel(ChatWindowViewModel chatWindowViewModel, IDailyData dailyData)
        {
            _dailyData = dailyData;
            InitChatBrokers();
            _chatWindowViewModel = chatWindowViewModel;
            Messenger.Default.Register<List<ChatMessage>>(this, MessageToken.NewChatMessageIn, ReceiveNewBrokerMessages);



            Messenger.Default.Register<List<ChatMessage>>(this, MessageToken.SendChatMessage, async (messages) =>
            {
                await AddNewBroker(messages);
            }); //当有未开启的中介消息时增加一下。
            ChatCheckBoxEventService.CheckComboBoxSelectionChanged -= OnCheckComboBoxSelectionChanged;

            ChatCheckBoxEventService.CheckComboBoxSelectionChanged += OnCheckComboBoxSelectionChanged;


            
            //StartSendCommand = new DelegateCommand(() =>
            //{
            //    StartTimer();
            //});
            //StopSendCommand = new DelegateCommand(() =>
            //{
            //    StopTimer();
            //});
        }

       



        #region 测试代码（并发） 240802 ，日后可以删除
        private System.Timers.Timer _testTimer;
        public DelegateCommand StartSendCommand { get; private set; }
        public DelegateCommand StopSendCommand { get; private set; }

        private void StartTimer()
        {
            if (_testTimer != null)
            {
                // 停止已有的定时器
                _testTimer.Stop();
                _testTimer.Dispose();
            }

            _messageCount = 0; // 重置消息计数器
            _messageCount++;
            // 初始化定时器
            _testTimer = new System.Timers.Timer(5000); // 每2000毫秒触发一次
            _testTimer.Elapsed -= OnTimerElapsedAsync;

            _testTimer.Elapsed += OnTimerElapsedAsync;
            _testTimer.AutoReset = true;
            _testTimer.Enabled = true;
        }

        private void StopTimer()
        {
            if (_testTimer != null)
            {
                // 停止定时器
                _testTimer.Stop();
                // 释放定时器资源
                _testTimer.Dispose();
                _testTimer = null;
                _messageCount = 0;
            }
        }

        private static readonly Dictionary<int, string> BrokerNames = new Dictionary<int, string>
{
    { 1, "国际" },
    { 2, "国利" },
    { 4, "平安" },
    { 6, "上田" }
};
        public int _messageCount = 0;
        private async void OnTimerElapsedAsync(object? sender, ElapsedEventArgs e)
        {

            var tasks = new List<Task>();

            foreach (var brokerId in BrokerNames.Keys)
            {
                // 根据 brokerId 获取对应的文字表示
                var brokerName = BrokerNames[brokerId];

                // 根据 brokerId 生成消息内容
                var messageContent = $"{brokerName}-{_messageCount}";

                var message = new QuanYiOrderServerResponseClass
                {
                    DataType = QuanYiServerBaseClass.DataTypeEnum.ChatMessage,
                    ChatMessage = messageContent,
                    BrokerID = brokerId,
                    UserID = UserHelper.UserID
                };

                // 将每个发送操作添加到任务列表中
                tasks.Add(Task.Run(() => Messenger.Default.Send(message, MessageToken.SendChatMessage)));
            }
            _messageCount++;
            // 等待所有任务完成
            await Task.WhenAll(tasks);
        }

        #endregion

        /// <summary>
        /// 当中介没打开时 新增窗口
        /// </summary>
        /// <param name="messages"></param>
        /// <returns></returns>
        private async Task AddNewBroker(List<ChatMessage> messages)
        {
            if(messages!=null&&messages.Count>0)
            {
                var brokerName = messages[0].BrokerName;

                if (ChatWindows.Any(vm => vm.ChatTitle == brokerName))
                {
                    return;
                    //Growl.WarningGlobal(item + "已经存在");
                }
                else
                {
                    // 模拟异步操作，例如数据库查询
                    await Task.Delay(20); // 异步等待，模拟数据库查询或其他异步操作

                    // 根据选中项添加新的 ChatWindowViewModel 到 ChatWindows
                    await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                    {
                        ChatWindows.Add(new ChatWindowViewModel(_dailyData, brokerName) { ChatTitle = brokerName });

                        var filteredBroker = OrderListViewModel.ChatReceivers
     .Where(broker => broker.Brokerid > 0 && !string.IsNullOrEmpty(broker.Company))
     .Select(broker => new ChatBroker
     {
         BrokerId = (int)broker.Brokerid,
         BrokerName = broker.Company,
         Icon = "\uEB68",
         UnreadMessageCount = 0,
         IsChecked = true
     }).FirstOrDefault();
                        BrokerChatList.Add(filteredBroker);
                    });

                    Messenger.Default.Send(brokerName, "AddNewBroker");
                    if (ChatWindows.Count <= 1)
                    {
                        UniformNumber = 1;
                    }
                    else
                    {
                        UniformNumber = 2;
                    }
                    await Task.Delay(1000);
                    Messenger.Default.Send(brokerName, MessageToken.ChatMessageBlink);
                    //Growl.InfoGlobal(item + "被选中了");
                }
            }

        }

        private async void OnCheckComboBoxSelectionChanged(object? sender, CheckComboBoxSelectionEventArgs e)
        {
            if (e.AddedItems != null)
            {
                foreach (var item in e.AddedItems)
                {
                    // 检查 ChatWindows 是否已经包含这个 ChatWindowViewModel
                    if (ChatWindows.Any(vm => vm.ChatTitle == item))
                    {
                        //Growl.WarningGlobal(item + "已经存在");
                    }
                    else
                    {
                        // 模拟异步操作，例如数据库查询
                        await Task.Delay(100); // 异步等待，模拟数据库查询或其他异步操作

                        // 根据选中项添加新的 ChatWindowViewModel 到 ChatWindows
                        ChatWindows.Add(new ChatWindowViewModel(_dailyData, item) { ChatTitle = item });
                        //Growl.InfoGlobal(item + "被选中了");
                    }
                }

                // 处理选中项的逻辑
            }

            if (e.RemovedItems != null)
            {
                foreach (var item in e.RemovedItems)
                {
                    // 查找并移除指定 ChatWindowViewModel
                    var viewModelToRemove = ChatWindows.FirstOrDefault(vm => vm.ChatTitle == item);
                    if (viewModelToRemove != null)
                    {
                        ChatWindows.Remove(viewModelToRemove);
                        //Growl.InfoGlobal(item + "被移除了");
                    }
                }
            }

            if (ChatWindows.Count <= 1)
            {
                UniformNumber = 1;
            }
            else
            {
                UniformNumber = 2;
            }
        }

        private void ReceiveNewBrokerMessages(List<ChatMessage> models)
        {
            if(models.Count>0)
            {
                var broker = this.BrokerChatList.Where(o => o.BrokerName.Contains(models[0].BrokerName)).FirstOrDefault();
                if(broker==null)
                {
                    Growl.ErrorGlobal("未找到可用中介" + models[0].BrokerName);
                }else
                {
                    if(broker.BrokerName!=TempBrokerName)//如果不是当前页面
                    {
                        broker.UnreadMessageCount += models.Count;
                    }

                }
    
            }

        }

        private void InitChatBrokers()
        {
            BrokerChatList = new ObservableCollection<ChatBroker>();
            var filteredBrokerList = OrderListViewModel.ChatReceivers
     .Where(broker => broker.Brokerid > 0 && !string.IsNullOrEmpty(broker.Company))
     .Select(broker => new ChatBroker
     {
         BrokerId = (int)broker.Brokerid,
         BrokerName = broker.Company,
         Icon = "\uEB68",
         UnreadMessageCount = 0,
         IsChecked = true
     })
     .ToList();

            // 清空并添加筛选后的Broker到BrokerChatList
            BrokerChatList.Clear();
            foreach (var broker in filteredBrokerList)
            {
                BrokerChatList.Add(broker);
            }
            BrokerList = BrokerChatList.Select(o => o.BrokerName).Distinct().ToList().ToObservableCollection();
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "信唐",BrokerId=1});
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "国利", BrokerId = 2});
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "国际", BrokerId = 3});
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "平安",BrokerId=4 });
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "信唐" });
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "中诚" });

            ChatWindows = new ObservableCollection<ChatWindowViewModel>();
            // Add some initial ChatWindowViewModels for demonstration purposes
            //ChatWindows.Add(new ChatWindowViewModel(_dailyData, "国利") { ChatTitle = "国利" });
            //ChatWindows.Add(new ChatWindowViewModel(_dailyData, "国际") { ChatTitle = "国际" });
            //ChatWindows.Add(new ChatWindowViewModel(_dailyData, "平安") { ChatTitle = "平安" });
            //ChatWindows.Add(new ChatWindowViewModel(_dailyData, "中诚") { ChatTitle = "中诚" });
            //ChatWindows.Add(new ChatWindowViewModel(_dailyData, "信唐") { ChatTitle="信唐" });

        }

        #region 初始化
        private void UpdateMainContent()
        {
            Messenger.Default.Register<object>(this, MessageToken.LoadShowContent, obj =>
            {
                if (SubContent is IDisposable disposable)
                {
                    disposable.Dispose();
                }
                SubContent = obj;
            });
        }

        private void UpdateLeftContent()
        {
            //clear status
            Messenger.Default.Register<object>(this, MessageToken.ClearLeftSelected, obj =>
            {
                //DemoItemCurrent = null;
                //foreach (var item in DemoInfoCollection)
                //{
                //    item.SelectedIndex = -1;
                //}
            });

            Messenger.Default.Register<object>(this, MessageToken.LangUpdated, obj =>
            {
                //if (DemoItemCurrent == null) return;
                //ContentTitle = LangProvider.GetLang(DemoItemCurrent.Name);
            });

            //加载数据
            Task.Factory.StartNew(() =>
                Task.Run(() =>
                {
                    MessageDataList = new ObservableCollection<ChatMessage> { new ChatMessage() };

                    //foreach (var item in _dataService.GetDemoInfo())
                    //{
                    //    PrismApplication.Current.Dispatcher.BeginInvoke(new Action(() =>
                    //    {
                    //        DemoInfoCollection.Add(item);
                    //    }), DispatcherPriority.ApplicationIdle);
                    //}
                }));
        }

        public string TempBrokerName = null;
        /// <summary>
        /// 根据不同中介刷新聊天框
        /// </summary>
        private async void RefreshChatBox(ChatBroker broker)
        {
            string brokerName = broker.BrokerName;
            var broker2 = this.BrokerChatList.Where(o => o.BrokerName.Contains(brokerName)).FirstOrDefault();
            if (broker2 != null)
            {
                broker2.UnreadMessageCount = 0;
            }
            //Messenger.Default.Send<string>(string.Empty, MessageToken.ClearChatWindow);
            //string brokerName = broker.BrokerName;
            //string info1 = brokerName;
            //TempBrokerName = info1;
            //Messenger.Default.Send(info1, MessageToken.SendChatMessage);
            //int brokerId = (int)OrderListViewModel.ChatReceivers.Where(o => o.Company == brokerName).FirstOrDefault().Brokerid;
            //List<ChatMessage> tempMessageList = new List<ChatMessage>();
            //tempMessageList = await Task.Run(() => _dailyData.GetAllMessageDataByBrokerId(brokerId, 0));

            //var broker2 = this.BrokerChatList.Where(o => o.BrokerName.Contains(brokerName)).FirstOrDefault();
            //if(broker2!= null)
            //{
            //    broker2.UnreadMessageCount = 0;
            //}
            //Messenger.Default.Send(tempMessageList, MessageToken.SendChatMessage);
        }


        #endregion
    }
    //public class ChatMessageViewModel:BindableBase
    //{
    //    #region 依赖属性
    //    private ObservableCollection<ChatBroker> brokerChatList;

    //    public ObservableCollection<ChatBroker> BrokerChatList
    //    {
    //        get { return brokerChatList; }
    //        set { brokerChatList = value; }
    //    }

    //    private ObservableCollection<ChatMessage> messageDataList;

    //    public ObservableCollection<ChatMessage> MessageDataList
    //    {
    //        get { return messageDataList; }
    //        set { messageDataList = value; }
    //    }


    //    private object subContent;

    //    public object SubContent
    //    {
    //        get { return subContent; }
    //        set { subContent = value; RaisePropertiesChanged(); }
    //    }

    //    #endregion


    //    #region 命令
    //    public DelegateCommand<ChatBroker> NavigateChatWindowCmd => new(RefreshChatBox);


    //    #endregion
    //    private readonly ChatWindowViewModel _chatWindowViewModel;

    //    public ChatMessageViewModel()
    //    {

    //    }
    //    private readonly IDailyData _dailyData;
    //    public ChatMessageViewModel(ChatWindowViewModel chatWindowViewModel,IDailyData dailyData)
    //    {
    //        _dailyData = dailyData;
    //        InitChatBrokers();
    //        _chatWindowViewModel = chatWindowViewModel;
    //        _chatWindowViewModel.ChatTitle = "我爱你";
    //    }

    //    private void InitChatBrokers()
    //    {
    //        BrokerChatList = new ObservableCollection<ChatBroker>();
    //        BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount=3,BrokerName="信唐" });
    //        BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount =0, BrokerName = "国利" });
    //        BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount =1, BrokerName = "国际" });
    //        BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount =2, BrokerName = "上田" });
    //        BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount =3, BrokerName = "信唐" });
    //        BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount =4, BrokerName = "中诚" });

    //    }

    //    #region 初始化
    //    private void UpdateMainContent()
    //    {
    //        Messenger.Default.Register<object>(this, MessageToken.LoadShowContent, obj =>
    //        {
    //            if (SubContent is IDisposable disposable)
    //            {
    //                disposable.Dispose();
    //            }
    //            SubContent = obj;
    //        });
    //    }

    //    private void UpdateLeftContent()
    //    {
    //        //clear status
    //        Messenger.Default.Register<object>(this, MessageToken.ClearLeftSelected, obj =>
    //        {
    //            //DemoItemCurrent = null;
    //            //foreach (var item in DemoInfoCollection)
    //            //{
    //            //    item.SelectedIndex = -1;
    //            //}
    //        });

    //        Messenger.Default.Register<object>(this, MessageToken.LangUpdated, obj =>
    //        {
    //            //if (DemoItemCurrent == null) return;
    //            //ContentTitle = LangProvider.GetLang(DemoItemCurrent.Name);
    //        });

    //     //加载数据
    //    Task.Factory.StartNew(() =>
    //        Task.Run(() =>
    //        {
    //            MessageDataList = new ObservableCollection<ChatMessage> { new ChatMessage() };

    //            //foreach (var item in _dataService.GetDemoInfo())
    //            //{
    //            //    PrismApplication.Current.Dispatcher.BeginInvoke(new Action(() =>
    //            //    {
    //            //        DemoInfoCollection.Add(item);
    //            //    }), DispatcherPriority.ApplicationIdle);
    //            //}
    //        }));
    //    }

    //    /// <summary>
    //    /// 根据不同中介刷新聊天框
    //    /// </summary>
    //    private void RefreshChatBox(ChatBroker broker)
    //    {
    //        Messenger.Default.Send<string>(string.Empty, MessageToken.ClearChatWindow);
    //        string brokerName = broker.BrokerName;
    //        string info1 = "broker" + brokerName;
    //        Messenger.Default.Send(info1, MessageToken.SendChatMessage);
    //        int brokerId = (int)OrderListViewModel.ChatReceivers.Where(o => o.Company == brokerName).FirstOrDefault().Brokerid;
    //        List<ChatMessage> tempMessageList = new List<ChatMessage>();
    //        tempMessageList = _dailyData.GetAllMessageDataByBrokerId(brokerId,108);

    //        Messenger.Default.Send(tempMessageList, MessageToken.SendChatMessage);
    //    }


    //    #endregion
    //}
}
